package org.spiderflow.logback;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.ThrowableProxy;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import org.spiderflow.common.context.SpiderContext;
import org.spiderflow.common.context.SpiderContextHolder;
import org.spiderflow.common.model.SpiderLog;
import org.spiderflow.model.SpiderWebSocketContext;

import java.util.Arrays;
import java.util.List;

/**
 * @author zsh
 */
public class SpiderFlowWebSocketAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {

    @Override
    protected void append(ILoggingEvent event) {
        SpiderContext context = SpiderContextHolder.get();
        if (!(context instanceof SpiderWebSocketContext)) {
            return;
        }
        SpiderWebSocketContext socketContext = (SpiderWebSocketContext) context;
        Object[] argumentArray = event.getArgumentArray() == null ? new Object[0] : event.getArgumentArray();
        List<Object> arguments = Arrays.asList(argumentArray);
        ThrowableProxy throwableProxy = (ThrowableProxy) event.getThrowableProxy();
        if (throwableProxy != null) {
            arguments.add(throwableProxy.getThrowable());
        }
        socketContext.log(new SpiderLog(event.getLevel().levelStr.toLowerCase(), event.getMessage(), arguments));
    }
}
